package com.gs.spring.core.domain.factory;

import java.util.Calendar;
import java.util.Date;
import java.util.Random;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.stereotype.Component;

import com.gs.spring.core.domain.Patient;
import com.gs.spring.core.domain.Person;

@Component(value="patientFactory")
public class PatientFactory implements FactoryBean<Patient> {

	/**
	 * The FactoryBean, not the factoried object itself, 
	 * lives in the Spring container and enjoys the lifecycle hooks and container services. 
	 * The returned instance is transient - Spring knows nothing about what you've returned from getObject() , 
	 * and will make no attempt to exercise any lifecycle hooks or anything else on it.
	 */
	public Patient getObject() throws Exception {
		//System.out.println("Returning patient from factory! But alas, the object is transient to the spring container so aop can be employed!");
		return getPatient();
	}

	public Class<?> getObjectType() {
		return Patient.class;
	}

	public boolean isSingleton() {
		return false;
	}

	private static Patient getPatient(){
		Patient patient = null;
		Person person =  null;
		String firstName = "First Name ";
		String lastName = "Last Name ";
		String code = "P-";
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		int random = 0;
		int dayOfYr = 0;
		do{
			random = getRandom();
			if(random<100){
				break;
			}
			cal.setTime(new Date());
			dayOfYr = (random%1000);
			cal.set(Calendar.DAY_OF_YEAR, (-1)*dayOfYr);
		}while(true);
		person = new Person(firstName+dayOfYr,lastName+dayOfYr,cal.getTime());
		patient = new Patient(Long.valueOf(dayOfYr),person,code+dayOfYr);
		return patient;
	}

	private static int getRandom() {
		Random r = new Random();
		return r.nextInt();
	}	
	
}
